package io.chance.receiverlei.channel;

import io.chance.receiverlei.main.AppStart;
import lrq.common.MyLog;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * 通道关闭处理器
 *
 * @author gislin
 */
public class ChannelCloseHandle extends SimpleChannelUpstreamHandler {

    static Logger connectLog = null;

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        if (connectLog == null) {
            connectLog = MyLog.getLogger(AppStart.connectLogName);
        }
        Channel channel = e.getChannel();
        String channelId = ChannelManager.getChannelId(channel);
        String mn = ChannelManager.getMN(channelId);
        ChannelManager.removeChannel(channelId);
        String ipAddress = channel.getRemoteAddress().toString();
        connectLog.info("设备:" + mn + ",IP:" + ipAddress + ",ID:" + ChannelManager.getChannelId(channel) + ",断开，移除");
        try {
            MessageDecode.errorDecodeTimes.remove(channel);
        }
        catch (Exception e1) {
            //
        }
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // TODO Auto-generated method stub
        super.channelClosed(ctx, e);
        if (connectLog == null) {
            connectLog = MyLog.getLogger(AppStart.connectLogName);
        }
        Channel channel = e.getChannel();
        String channelId = ChannelManager.getChannelId(channel);
        String mn = ChannelManager.getMN(channelId);
        ChannelManager.removeChannel(channelId);
        String ipAddress = channel.getRemoteAddress().toString();
        connectLog.info("设备:" + mn + ",IP:" + ipAddress + ",ID:" + ChannelManager.getChannelId(channel) + ",关闭，移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext arg0, org.jboss.netty.channel.ExceptionEvent arg1) throws Exception {

    }

    ;
}
